package com.example.accessingdatamysql.conf;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.persistence.EntityManager;

/**
 * @author caiwl
 * @date 2020/4/14 10:13
 */
@Configuration
@MapperScan(
        basePackages = {"com.example.accessingdatamysql.second"},
        sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondMBConfig {

    @Bean
    @ConfigurationProperties(prefix = "app.datasource.second")
    public HikariDataSource secondDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory customSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(secondDataSource());
        return bean.getObject();
    }

    @Bean(name = "secondTransactionManager")
    public PlatformTransactionManager customTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource());
    }
}
